package com.titaniume.sync;

import sun.security.provider.SHA;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.sync
 * @ClassName: ThreadDemo1
 * @Author: huangrenfei
 * @Description: 线程直接的通信 交替改变变量的值
 * @Date: 2021/11/22 13:11
 * @Version: 1.0
 */

//第一步 创建资源类，定义属性和操作方法
class  Share{

    //初始值
    private int number =0;
    //+1的方法
    public  synchronized void incr() throws InterruptedException {
        //第二步 判断 干活 通知
        //条件判断放在while循环 防止出现虚假唤醒问题
        while (number!=0){
            this.wait(); //在哪里睡 ，就在哪里醒
        }

        //如果number是0,就+1 操作
        number++;
        System.out.println(Thread.currentThread().getName() +" ::" + number);
        //通知其他线程
        this.notifyAll();
    }

    //-1的方法
    public  synchronized void decr() throws InterruptedException {
        //判断
        while(number!=1){
            this.wait();
        }

        //如果number是1,就-1 操作
        //干活
        number--;
        System.out.println(Thread.currentThread().getName() +" ::" + number);
        //通知其他线程
        //通知
        this.notifyAll();
    }



}

public class ThreadDemo1 {

    public static void main(String[] args) {

        //第三步 创建多个线程 调用资源类的操作方法
        Share share = new Share();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();


        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();


        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();

    }
}
